<?php if (! defined('BASEPATH')) exit('No direct script access allowed');

	class Admin_Model extends MY_Model{
		
		public $table;
		public $module;
		public $status_name = 'status';
		public $list_view_condition = '';
		public $list_view_searched_fields = array();
		public $list_view_searched_filter = array();
		public $form_view_fields = array();
		protected $checkExistField = array();
		protected $listUploadField = array();
		
		
		function getsearchContent($limit, $page, $fields) {
			$order_by = $this->input->post('order_by');
			$func_order_by = $this->input->post('func_order_by');
			
			
			if($this->module == 'accounts'){
				$this->db->select($this->table.'.*, '.ADMIN_GROUP_TABLE.'.name as group_name');
				$this->db->join(ADMIN_GROUP_TABLE, ADMIN_GROUP_TABLE.'.id='.$this->table.'.group_id','LEFT');
				if($this->session->userdata('userInfo')!='root'){
					$this->db->where('username != "root"');
				}
			} else {
				$this->db->select('*');
				if(!empty($this->list_view_condition)){
					$this->db->where($this->list_view_condition);
				}
			}
			
			$this->db->limit($limit, $page);
			$this->db->order_by($func_order_by, $order_by);
			
			$this->getSearchCriteria($fields);
			$query = $this->db->get($this->table);

			if ($query->result()) {
				return $query->result();
			} else {
				return FALSE;
			}
		}
		
		function getSearchCriteria($fields){
			if($fields == 'all'){
				$fields = $this->list_view_searched_fields;
			} else {
				foreach($this->list_view_searched_fields as $field => $title){
					if($field == $fields){
						$fields = array($field	=>	$title);
					}
				}
			}
			
			$content = $this->input->post('content');
			$dateTo = $this->input->post('dateTo');
			$dateFrom = $this->input->post('dateFrom');

			$db = &$this->db;
			if ($content != '' && $content != SEARCH_TEXTBOX_MESSAGE) {
				if(is_array($fields) && count($fields) > 0){
					$tempCount = 0;
					foreach($fields as $field	=>	$title){
						$tempCount++;
						if($tempCount == 1){
							$db->where('(`'.$field.'` LIKE "%' . $content . '%")');
						}else{
							$db->or_where('(`'.$field.'` LIKE "%' . $content . '%")');
						}
					}
				}
			}

			if(!empty($this->list_view_searched_filter)){
				if(isset($this->list_view_searched_filter['sub_filter'])){
					//sub filter
					if($this->input->post('sub_filter_' . $this->list_view_searched_filter['sub_filter']['name']) != 'all')
						$db->where($this->list_view_searched_filter['sub_filter']['name']." = " . $this->input->post('sub_filter_' . $this->list_view_searched_filter['sub_filter']['name']) );
				}
				else{
					if($this->input->post('search_filter_' . $this->list_view_searched_filter['name']) != 'all')
						$db->where($this->list_view_searched_filter['name']." = " . $this->input->post('search_filter_' . $this->list_view_searched_filter['name']) );
				}
				
			}
			if ($this->input->post('dateFrom') != '' && $this->input->post('dateTo') == '') {
				$db->where('created >= "' . date('Y-m-d 00:00:00', strtotime($dateTo)) . '"');
			}
			if ($this->input->post('dateFrom') == '' && $this->input->post('dateTo') != '') {
				$db->where('created <= "' . date('Y-m-d 23:59:59', strtotime($dateTo)) . '"');
			}
			if ($this->input->post('dateFrom') != '' && $this->input->post('dateTo') != '') {
				$db->where('created >= "' . date('Y-m-d 00:00:00', strtotime($dateFrom)) . '"');
				$db->where('created <= "' . date('Y-m-d 23:59:59', strtotime($dateTo)) . '"');
			}
		}
		
		function getTotalsearchContent($fields) {
			$content = $this->input->post('content');
			$dateTo = $this->input->post('dateTo');
			$dateFrom = $this->input->post('dateFrom');

			$this->db->select('*');
			if(!empty($this->list_view_condition)){
				$this->db->where($this->list_view_condition);
			}
			$this->getSearchCriteria($fields);
			$query = $this->db->count_all_results($this->table);

			if ($query > 0) {
				return $query;
			} else {
				return FALSE;
			}
		}
		
		function getTotalContent() {
			$content = $this->input->post('content');
			$dateTo = $this->input->post('dateTo');
			$dateFrom = $this->input->post('dateFrom');

			$this->db->select('*');
			if(!empty($this->list_view_condition)){
				$this->db->where($this->list_view_condition);
			}
			$query = $this->db->count_all_results($this->table);
			if ($query > 0) {
				return $query;
			} else {
				return FALSE;
			}

		}
		
		function getDetailManagement($id){
			$this->db->select('*');
			$this->db->where('id',$id);
			$query = $this->db->get($this->table);

			if($query->row()){
				return $query->row();
			}else{
				return false;
			}
		}
		
		function saveManagement($raw_data=''){
			$obj_id = 0;
			if($this->input->post('hiddenIdAdmincp')==0){
				$this->admincp_checkDataExist();
				$data = $this->getFormData($raw_data['FILES']['fileName'], $raw_data['custom']);

				if($this->db->insert($this->table,$data)){
					$obj_id =  $this->db->insert_id();
					modules::run('admincp/saveLog',$this->module,$obj_id,'Add new','Add new');
				}
			} else {
				$obj_id = (int)($this->input->post('hiddenIdAdmincp'));
				//pr($result);
				$obj = $this->model->get('*',$this->table,"id = {$obj_id}");
				if(!empty($obj)){
					$this->admincp_checkDataExist($obj);
					//pr($obj);

					$hinh=array('image','images_hover','images_thumb');
						foreach ($hinh as $view_img) {
							$del=$this->deleteImage($obj,$this->input->post('delete_'.$view_img));
						}

					$data = $this->getFormData($raw_data['FILES']['fileName'], $raw_data['custom'], 'edit');
					
					//Xử lý xóa hình khi update thay đổi hình
					if(!empty($result)){
						if(!empty($raw_data['FILES']['fileName'])){
							foreach($raw_data['FILES']['fileName'] as $k=>$v){
								@unlink('static/uploads/'.$this->module.'/' .$raw_data['FILES']['fileOption'][$k]. '/'.$result->$k);
								$data[$k] = $raw_data['FILES']['fileName'][$k];
							}
						}
						modules::run('admincp/saveLog',$this->module,$this->input->post('hiddenIdAdmincp'),'','Update',$result,$data);
					}
					$this->db->where('id',$this->input->post('hiddenIdAdmincp'));
					if(!$this->db->update($this->table,$data)){
						$obj_id = 0; // False result
					}
				}
			}
			return $obj_id;
		}

		function deleteImage($obj,$linkimg=''){
			if(!empty($obj)){
						//$hinh=array('images','image','images_hover','images_thumb');
						//foreach ($hinh as $view_img) {
							foreach ($obj as $key => $link_images) {
								if($linkimg){
									//echo $link_images;
										@unlink('static/uploads/'.$this->module.'/image/' .$link_images);
										$link_images='';
										if($this->module=='categories'){
											$r=array(
												'images'=>$link_images,
												'images_hover'=>$link_images
													);
										}elseif($this->module=='gallery'){
											$r=array(
												'image'=>$link_images,												
													);
										}else{
											$r=array(
												'images'=>$link_images,												
												'images_thumb'=>$link_images												
													);											
										}
										
										$this->db->where('id',$this->input->post('hiddenIdAdmincp'));
										$this->db->update($this->table,$r);
										
								}
							}
						//}
					}
		}
		
		function checkDataExist($field,$data){
			$this->db->select('id');
			$this->db->where($field,$data);
			$this->db->limit(1);
			$query = $this->db->get($this->table);

			if($query->result()){
				return true;
			}else{
				return false;
			}
		}
		
		function getVarModel($name){
			if(isset($this->$name)){
				return $this->$name;
			}else{
				return FALSE;
			}
			
		}
		
	public function getFormData($fileName ='', $customData = '',$type = 'insert'){
		$data = array();
		foreach($this->form_view_fields as $col => $obj){
			// Set default values
			$obj['func'] = !empty($obj['func']) ? $obj['func'] : '';
			switch($obj['type']){
				case 'text' :
				case 'textarea' :
				case 'custom' :
					if(empty($obj['func'])){
						$data[$col] = $this->input->post($obj['name']);
					} else {
						$data[$col] = $this->dataProcess($this->input->post($obj['name']), $obj['func']);
					}
				break;
				
				case 'select' :
					if(isset($obj['sub_select'])){
						if(empty($obj['sub_select']['func'])){
							$data[$obj['sub_select']['name']] = $this->input->post($obj['sub_select']['name']);
						}
						else{
							$data[$obj['sub_select']['name']] = $this->dataProcess($this->input->post($obj['sub_select']['name']), $obj['sub_select']['func']);
						}
					}
					if(empty($obj['func'])){
						$data[$col] = $this->input->post($obj['name']);
					} else {
						$data[$col] = $this->dataProcess($this->input->post($obj['name']), $obj['func']);
					}
				break;
				
				case 'checkbox' :
					if($this->input->post($obj['name'])=='on'){
						$status = 1;
					}else{
						$status = 0;
					}
					$data[$col] = $status;
				break;
				
				case 'password' :
					if($type == 'insert')
						$data[$col] = $this->dataProcess($this->input->post($obj['name']), $obj['func']);
					else{
						if($this->input->post($obj['name']) !='')
							$data[$col] = $this->dataProcess($this->input->post($obj['name']), $obj['func']);
					}
				break;
			}
		}
		if($fileName != '' && is_array($fileName)){
			foreach($fileName as $k=>$v){
				$data[$k] = $v;
			}
		}
		//more data
		if($customData !='' && is_array($customData)){
			foreach($customData as $k=>$v){
				$data[$k] = $v;
			}
		}
		if($type =='insert')
			$data['created'] = date('Y-m-d H:i:s');
		return $data;
	}
	
	function dataProcess($str, $type=''){
		switch($type){
			case 'slug' :
			return SEO($str);
			
			case 'upper' :
			return mb_strtoupper($str , 'UTF-8');
			
			case 'password' :
			return md5($str);
			
			case 'date' :
			return date('Y-m-d H:i:s', strtotime($str));

			default :
			return $str;
		}
	}


	function admincp_checkDataExist($result=''){
		if(count($this->checkExistField > 0)){
			foreach($this->checkExistField as $k => $v){
				if($result != ''){
					if($result->$k != $this->input->post($v))
						if($this->checkDataExist($k,$this->input->post($v))){
							print 'error-'.$k.'-exists';
							exit;
						}
				}
				else{
					if($this->checkDataExist($k,$this->input->post($v))){
						print 'error-'.$k.'-exists';
						exit;
					}
				}
				
			}
		}
	}
		/*------------------------------------ Begin Admin GALLERY ------------------------------------*/
	
		function getListImageOfGallery($category_id, $table = ''){
		$this->db->select('id,image');
		$this->db->where('category_id',$category_id);
		$this->db->order_by('created','DESC');
		$query = $this->db->get(PREFIX.$table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}
	
	function getDetailImageOfGallery($id, $table = ''){
		$this->db->select('*');
		$this->db->where('id',$id);
		$query = $this->db->get(PREFIX.$table);

		if($query->row()){
			return $query->row();
		}else{
			return false;
		}
	}

	/*------------------------------------ End Admin GALLERY ------------------------------------*/

	/*------------------------------------ Begin Admin Manager Modules ------------------------------------*/
	function check_modules($module){
		$this->db->select('id,name');
		$this->db->where('name_function',$module);
		$query = $this->db->get($this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}
	
	function list_module(){
		$this->db->select('*');
		$this->db->where($this->status_name,1);
		$this->db->order_by('name','ASC');
		$query = $this->db->get($this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}
	/*------------------------------------ End Admin Manager Modules ------------------------------------*/

}